package helper;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import signals.* ;

public class SignalSender extends JFrame implements ActionListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static int UDP_PORT = 5500 ;
	
	static InetAddress[] receivers = null ;
	
	static {
		receivers = new InetAddress[1] ;
		try {
			receivers[0] = InetAddress.getByName("127.0.0.1") ;
		}
		catch (UnknownHostException e) {
			e.printStackTrace();
			System.exit(1) ;
		}
	}

	private Signal[] m_signals = {new Hello("User Test"), new HelloReply("User Reply"), new GoodBye(), 
			                      new AskLogin(), new SendText("Test Message", receivers)} ;
	
	private ArrayList <JButton> m_buttons = new ArrayList <JButton> ();
	
	public SignalSender() {
		setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)) ;
		for (Signal s : m_signals) {
			JButton button = new JButton(s.getClass().toString()) ;
			button.addActionListener(this) ;
			m_buttons.add(button) ;
			add(button) ;
			button.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE)) ;
			button.setAlignmentX(JButton.CENTER_ALIGNMENT) ;
		}
		setSize (200, 200) ;
		setResizable(false) ;
		setTitle("Chat System Test Program") ;
		setDefaultCloseOperation(EXIT_ON_CLOSE) ;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		for (int i=0; i<m_buttons.size(); i++) {
			if (e.getSource() == m_buttons.get(i)) {
				byte[] sbytes = m_signals[i].serialize() ;
				try {
					DatagramPacket pa = new DatagramPacket(sbytes, sbytes.length, new InetSocketAddress("localhost", UDP_PORT)) ;
					DatagramSocket dso = new DatagramSocket() ;
					dso.send(pa) ;
					dso.close () ;
				} 
				catch (SocketException e1) {
					e1.printStackTrace();
				} 
				catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static void main (String[] args) {
		(new SignalSender()).setVisible(true) ;
	}

}
